<?php

/**
 * Class Lib_FlashSMS_Main
 * 短信发送主类
 * 2022/08/01
 */
class Lib_FlashSMS_Main
{

    private static $_mobile = null;
    /**
     * 发送短信接口
     * @param $mobile array   手机号
     * @param array code
     * @return array
     * @throws Exception
     */
    public static function sendSMS($mobile)
    {
        try {
            //手机号码校验
            $mobile = Lib_FlashSMS_Base_Tool::checkmobile($mobile);
            if(empty($mobile)){
                return self::errorReturn(5501,'号码不能为空');
            }
            //使用的通道
            $pass = Lib_FlashSMS_Config::$use_pass;
            $content = Lib_FlashSMS_Config::$sms_content[$pass['content']];
            $sign = Lib_FlashSMS_Config::$sms_sign[$pass['sign']];
            if (empty($content) || empty($sign)) {
                return self::errorReturn(5502,'通道配置不能为空');
            }
            //主通道发送短信
            $pass_obj = Lib_FlashSMS_Adapter::getAdapter($pass['pass']);
            $res = $pass_obj->sendSMS($mobile,$content,$sign);
            if ($res['code'] ==  200) {
                return array('code' => 200, 'message' => '发送成功');
            }
            return array('code' => 400, 'message' => empty($res['message']) ? '' : $res['message']);
        }catch (Exception $exception) {
            Func_Log::write('SMS','Exception：'.$exception->getMessage(),'res='.json_encode([$mobile,$scene,$argv,$case_id,$extra]));
            return array('code' => 500, 'message' => $exception->getMessage());
        }

    }


    public static function errorReturn($code,$message='')
    {
        return array('code' => $code, 'message' => $message);
    }

    public static function curlPost($url, $params, $header_arr=[])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_arr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $res = curl_exec($ch);

        //请求超时
        if ($res == false && curl_errno($ch) == 28) {
            curl_close($ch);
            return 28;
        }
        curl_close($ch);
        return $res;
    }
}